package com.shqcjd.preinstallglass.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.pojo.IntentEquipmentBean;
import com.shqcjd.preinstallglass.model.pojo.RouteListBean;
import com.shqcjd.preinstallglass.model.pojo.TaskCodeBean;
import com.shqcjd.preinstallglass.ui.activity.remote.ExpertTypeActivity;
import com.shqcjd.preinstallglass.ui.adapter.RouteAdapter;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.Config;
import com.shqcjd.preinstallglass.util.PrefUtils;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RouteActivity extends BaseActivity {
    private static final int REQUEST_CODE_RANDOM = 10003;
    @BindView(R.id.rv_route)
    RecyclerView rvRoute;
    @BindView(R.id.ib_guide)
    Button ibGuide;
    @BindView(R.id.ib_inspection)
    Button ibInspection;
    private Context context;
    private RouteAdapter routeAdapter;
    private int randomTaskId = -1;
    List<RouteListBean.ItemsBean> mList = new ArrayList<>();
    private String userCode;
    private boolean isFirst = true;


    @BindView(R.id.mainUpView1)
    MainUpView mMainUpView;
    @BindView(R.id.main_lay)
    FrameMainLayout main_lay11;
    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_route;
    }

    @Override
    public void initView() {
        super.initView();
        context = this;

        initAdapter();

        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpView.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpView.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpView.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.


        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpView.setFocusView(newFocus, mOldFocus, 1.0f);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });
        rvRoute.setFocusable(false);
        rvRoute.setFocusableInTouchMode(false);
        ibGuide.setNextFocusRightId(R.id.ib_inspection);
        ibInspection.setNextFocusLeftId(R.id.ib_guide);
    }

    private void initAdapter() {
        rvRoute.setLayoutManager(new LinearLayoutManager(context));
        routeAdapter = new RouteAdapter();
        rvRoute.setAdapter(routeAdapter);
        routeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String userCode = PrefUtils.getString(context, PrefUtils.USER_CODE, null);
                if (userCode == null || userCode.equals("88888888")) {
                    showDelDialog();
                    return;
                }

                RouteListBean.ItemsBean item = (RouteListBean.ItemsBean) adapter.getItem(position);
                //判断路线是否可巡检
                if (item.task_id != null) {
                    randomTaskId  = item.task_id;
                    RxPermissions permissions = new RxPermissions(RouteActivity.this);
                    permissions.setLogging(true);
                    permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        //每次调用相机都需要调用该方法
                                        startActivityForResult(new Intent(RouteActivity.this, QRcodeActivity.class), REQUEST_CODE_RANDOM);
                                    } else {
                                        ToastUtils.show(RouteActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                    }
                                }
                            });
                } else {
                    ToastUtils.showShort(context,"当前路线不可巡检状态");
                }

            }
        });
    }

    private void showDelDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_del_view, false)
                .show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = 630;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialog.onWindowAttributesChanged(lp);
        window.setAttributes(lp);

        View customeView = dialog.getCustomView();

        TextView tv_title = customeView.findViewById(R.id.tv_title);
        Button follow = (Button) customeView.findViewById(R.id.btn_follow);
        Button cancel = customeView.findViewById(R.id.btn_cancel);

        tv_title.setText("开放功能请联系我们\n联系电话:021-62596228");
        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected boolean isAutomaticInitVoice() {
        return false;
    }

    @Override
    public void initData() {
        getRouteList();
    }

    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果----:"+result);
        if(result.equals("返回")){
            finish();
        }else if(result.equals("远程指导")){
            ibGuide.performClick();
        }else if (result.equals("随机巡检")){
            ibInspection.performClick();
        }else{
            voiceResult(result);
        }
    }

    //"|返回|保存|拍照|输入|删除;"
    private String addVoiceContent(){
        String str = "";
        for(int i=1; i<=mList.size(); i++){
            str = str + "|选择"+i;
        }
        return str + "|返回|远程指导|随机巡检;";
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!isFirst){
            getVoiceContent(addVoiceContent());
        }
        if(isFirst){
            isFirst = false;
        }
    }

    private void voiceResult(String result){
        for(int i=1; i<=mList.size(); i++){
            if(result.equals("选择"+i)){
                RouteListBean.ItemsBean item = (RouteListBean.ItemsBean) mList.get(i-1);

                userCode = PrefUtils.getString(context, PrefUtils.USER_CODE, "");
                if (userCode.isEmpty() || userCode.equals("88888888")) {
                    showDelDialog();
                    return;
                }


                //判断路线是否可巡检
                if (item.task_id != null) {
                    randomTaskId  = item.task_id;
                    RxPermissions permissions = new RxPermissions(RouteActivity.this);
                    permissions.setLogging(true);
                    permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean aBoolean) throws Exception {
                                    if (aBoolean) {
                                        //每次调用相机都需要调用该方法
                                        startActivityForResult(new Intent(RouteActivity.this, QRcodeActivity.class), REQUEST_CODE_RANDOM);
                                    } else {
                                        ToastUtils.show(RouteActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                    }
                                }
                            });
                } else {
                    ToastUtils.showShort(context,"当前路线不可巡检状态");
                }
                return;
            }
        }
    }

    private void getRouteList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", "1");
        map.put("pageSize", "10000");
        map.put("patrol_root_name", "");
        ApiService.routeListHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<RouteListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<RouteListBean> retData) {
                        if (retData.retCode == 10000) {
                            mList = retData.data.items;
                            routeAdapter.setNewData(mList);
                            getVoiceContent(addVoiceContent());
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(context, errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    @OnClick({R.id.ib_guide, R.id.ib_inspection})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.ib_guide://远程指导
                userCode = PrefUtils.getString(context, PrefUtils.USER_CODE, "");
                if (userCode.isEmpty() || userCode.equals("88888888")) {
                    showDelDialog();
                    return;
                }
                startActivity(new Intent(context, ExpertTypeActivity.class));

                break;
            case R.id.ib_inspection:// 随机巡检
                userCode = PrefUtils.getString(context, PrefUtils.USER_CODE, "");
                if (userCode.isEmpty() || userCode.equals("88888888")) {
                    showDelDialog();
                    return;
                }
                randomInspection();
                break;
        }
    }

    private void randomInspection() {
        ApiService.getRandomTask()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TaskCodeBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<TaskCodeBean> responseData) {
                        if (responseData.retCode != 10000) {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        randomTaskId = responseData.data.task_id;
                        RxPermissions permissions = new RxPermissions(RouteActivity.this);
                        permissions.setLogging(true);
                        permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(Boolean aBoolean) throws Exception {
                                        if (aBoolean) {
                                            //每次调用相机都需要调用该方法
                                            startActivityForResult(new Intent(RouteActivity.this, QRcodeActivity.class), REQUEST_CODE_RANDOM);
                                        } else {
                                            ToastUtils.show(RouteActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                        }
                                    }
                                });
                    }


                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE_RANDOM == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            //扫描任务码
            handleEquipment(value);

        }
    }

    private void handleEquipment(String value) {
        if (!UIUtils.isJSONValid(value)){
            qCode(value);
        }else{
            Toast.makeText(context, "设备扫描错误", Toast.LENGTH_SHORT).show();
        }
    }

    public void qCode(String kksStr){
        if(randomTaskId!=-1){
            isInspectionData(kksStr);
        }else{
            Toast.makeText(context, "当前任务不存在", Toast.LENGTH_SHORT).show();
        }
    }

    private void isInspectionData(String kksStr){
        ApiService.intentEquipmentHttp(kksStr.replace("#", "%23"), randomTaskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if(responseData.retCode==10000){
                            if(responseData.data.check_gps){
                                RxPermissions permissions = new RxPermissions(RouteActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if(distance<Config.INSPECTION_DISTANCE){
                                                            if(responseData.data.isgroup){
                                                                Intent it = new Intent(context, InspectionStandardActivity.class);
                                                                it.putExtra("kks", kksStr);
                                                                it.putExtra("tId", randomTaskId);
                                                                startActivity(it);
                                                            }else{
                                                                Intent it = new Intent(context, NewEquipmentInspectionActivity.class);
                                                                it.putExtra("tId", randomTaskId);
                                                                it.putExtra("kks", kksStr);
                                                                startActivity(it);
                                                            }
                                                            }else{
                                                                Toast.makeText(context, "当前位置距离巡检点超过了"+Config.INSPECTION_DISTANCE+"米", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(context, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });

                            }else{
                                hideWaitingDialog();
                                if(responseData.data.isgroup){
                                    Intent it = new Intent(context, InspectionStandardActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", randomTaskId);
                                    startActivity(it);
                                }else{
                                    Intent it = new Intent(context, NewEquipmentInspectionActivity.class);
                                    it.putExtra("tId", randomTaskId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                            }


                        }else{
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
